<?php
/**
 * erp近14个月的销售额报表 (erp)
 */
namespace App\Logic\SalesReport;

use App\Models\Basics\AmazonAccount;
use App\Models\Basics\RakutenAccount;
use App\Models\Basics\ShopifyAccount;
use App\Models\Basics\SysICountry;
use App\Models\Basics\SysPlat;
use App\Models\Basics\SysPlatAccount;
use App\Models\Basics\SysPlatCountry;
use App\Models\SalesReport\MonthlySa;
use App\Models\SalesAmazon\SalesAmountMonth;
use Illuminate\Support\Facades\DB;
class MonthlySalesAmount
{
    public static function init(){

        $amazonPlat = SysPlat::PLAT_AMAZON;
        $shopifyPlat = SysPlat::PLAT_SHOPIFY;
        $rakutenPlat = SysPlat::PLAT_RAKUTEN;
        try{
            $start = date('Ym',strtotime('midnight first day of -14 month'));
            $end = date('Ym');

            MonthlySa::query()->truncate(); //重置月销售额（月）（近14个月）

            DB::beginTransaction();
            //amazon
            $i = 0;
            $num = 100;
            $area = [];
            $account = AmazonAccount::optionsForApi();
            while(true){
                if($account->isEmpty())break;
                $_account = $account->splice($i,$num);
                foreach($_account as $__account){
                    $countryIds = SysPlatAccount::getCountriesById($__account->id);
                    foreach ($countryIds as $countryId){
                        $sam = SalesAmountMonth::query()
                            ->where('plat_id',$amazonPlat)
                            ->where('account_id',$__account->id)
                            ->where('country_id',$countryId)
                            ->whereBetween('month',[$start,$end])
                            ->select('month',DB::raw('sum(amount) as amount'))
                            ->groupBy('month')
                            ->pluck('amount','month')
                            ->toArray();

                        if(!array_key_exists($countryId,$area)){
                            $area[$countryId] = SysICountry::getAreaIdByCountryId($countryId);
                        }
                        $monthlySaTotal = [];
                        $monthlySaTotal['area_id'] = $area[$countryId];//店铺站点
                        for($i = 14;$i >= 0;$i--){
                            $date = date('Ym',strtotime("midnight first day of -{$i} month"));
                            $monthlySaTotal['month'.$i] = array_key_exists($date,$sam) ? $sam[$date] : 0;
                        }
                        MonthlySa::query()->updateOrCreate([
                            'plat_id' => $amazonPlat,
                            'account_id' => $__account->id,
                            'country_id' => $countryId
                        ],$monthlySaTotal);
                    }
                }
            }
            sleep(2);

            //shopify
            $i2 = 0;
            $num2 = 100;
            $shopifyAreaId = 1; //US站点
            $shopifyCountryId = 1; //US国家
            $account = ShopifyAccount::optionsForApi();
            while(true){
                if($account->isEmpty())break;
                $_account = $account->splice($i2,$num2);
                foreach($_account as $__account){
                    $sam = SalesAmountMonth::query()
                        ->where('plat_id',$shopifyPlat)
                        ->where('account_id',$__account->id)
                        //->where('country_id',$countryId)
                        ->whereBetween('month',[$start,$end])
                        ->select('month',DB::raw('sum(amount) as amount'))
                        ->groupBy('month')
                        ->pluck('amount','month')
                        ->toArray();

                    $monthlySaTotal = [];
                    $monthlySaTotal['area_id'] = $shopifyAreaId;//店铺站点
                    for($i = 14;$i >= 0;$i--){
                        $date = date('Ym',strtotime("midnight first day of -{$i} month"));
                        $monthlySaTotal['month'.$i] = array_key_exists($date,$sam) ? $sam[$date] : 0;
                    }
                    MonthlySa::query()->updateOrCreate([
                        'plat_id' => $shopifyPlat,
                        'account_id' => $__account->id,
                        'country_id' => $shopifyCountryId
                    ],$monthlySaTotal);
                }
            }
            sleep(2);

            //rakuten
            $i3 = 0;
            $num3 = 100;
            $rakutenAreaId = 6; //JP站点
            $rakutenCountryId = 12; //JP国家
            $rakutenAccount = RakutenAccount::optionsForApi();
            while(true){
                if($rakutenAccount->isEmpty())break;
                $_account = $rakutenAccount->splice($i3,$num3);
                foreach($_account as $__account){
                    $sam = SalesAmountMonth::query()
                        ->where('plat_id',$rakutenPlat)
                        ->where('account_id',$__account->id)
                        //->where('country_id',$countryId)
                        ->whereBetween('month',[$start,$end])
                        ->select('month',DB::raw('sum(amount) as amount'))
                        ->groupBy('month')
                        ->pluck('amount','month')
                        ->toArray();

                    $monthlySaTotal = [];
                    $monthlySaTotal['area_id'] = $rakutenAreaId;//店铺站点
                    for($i = 14;$i >= 0;$i--){
                        $date = date('Ym',strtotime("midnight first day of -{$i} month"));
                        $monthlySaTotal['month'.$i] = array_key_exists($date,$sam) ? $sam[$date] : 0;
                    }
                    MonthlySa::query()->updateOrCreate([
                        'plat_id' => $rakutenPlat,
                        'account_id' => $__account->id,
                        'country_id' => $rakutenCountryId
                    ],$monthlySaTotal);
                }
            }
            sleep(2);

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }
}
